﻿using System;
using System.Web.Mvc;

namespace dPet.Web.Hospital.Controllers
{
	using dPet.Application.DataObjects;
	using dPet.Application.Services;
	using dPet.Infrastructure.Logging;
	using dPet.Web.Hospital.Fliters;
	using dPet.Web.Hospital.ViewModels;
	using Hangerd.Mvc;
	using Hangerd.Mvc.Authentication;
	using Hangerd.Mvc.ViewModels;

	public class AccountController : HangerdController
	{
		private readonly IAccountService _accountService;
		private readonly ILoginLoggingService _loginLoggingService;

		public AccountController(
			IAccountService accountService,
			ILoginLoggingService loginLoggingService)
		{
			_accountService = accountService;
			_loginLoggingService = loginLoggingService;
		}

		public ActionResult Login(string returnUrl = null)
		{
			ViewBag.ReturnUrl = returnUrl;

			return View();
		}

		[HttpPost]
		public ActionResult Login(LoginModel model, string returnUrl = null)
		{
			var staff = _accountService.GetStaff(model.LoginName, model.Password);

			if (staff == null)
			{
				return base.AlertAndRedirect("登录邮箱或密码错误", "/Account/Login");
			}

			LoginHelper.Login(staff.Id, string.Empty, DateTime.Now.AddHours(2));

			//登录日志
			_loginLoggingService.AddLog(model.LoginName, base.Request);

			if (!string.IsNullOrWhiteSpace(returnUrl) && Url.IsLocalUrl(returnUrl) && returnUrl.StartsWith("/")
				&& !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
			{
				return base.AlertAndRedirect(string.Empty, returnUrl);
			}

			return base.RedirectToAction("Index", "Home");
		}

		public ActionResult SignOut()
		{
			LoginHelper.SignOut();

			return RedirectToAction("Login");
		}

		[StaffLoginAuth]
		public ActionResult ChangePassword()
		{
			return View();
		}

		[HttpPost]
		[StaffLoginAuth]
		public ActionResult ChangePassword(string oldPassword, string newPassword)
		{
			var loginStaff = LoginStaffModel.Current;
			var result = _accountService.ChangeStaffPassword(loginStaff.Id, oldPassword, newPassword, loginStaff);

			return base.AlertAndRedirect(result.Message, "/Account/ChangePassword");
		}

		[StaffLoginAuth]
		public ActionResult Profile()
		{
			return View(LoginStaffModel.Current);
		}

		[HttpPost]
		[StaffLoginAuth]
		public ActionResult SaveProfile(StaffDto staffDto)
		{
			var loginStaff = LoginStaffModel.Current;
			var result = _accountService.UpdateStaff(loginStaff.Id, staffDto, loginStaff);

			return base.AlertAndRedirect(result.Message, "/Account/Profile");
		}
	}
}
